/***** BEGIN LICENSE BLOCK *****
 * Version: CPL 1.0/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Common Public
 * License Version 1.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.eclipse.org/legal/cpl-v10.html
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
 * Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
 * Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
 * Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
 * Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
 * Copyright (C) 2004 Joey Gibson <joey@joeygibson.com>
 * Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
 * Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
 * Copyright (C) 2005 David Corbin <dcorbin@users.sf.net>
 * Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
 * 
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the CPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the CPL, the GPL or the LGPL.
 ***** END LICENSE BLOCK *****/
package asruby.lang {

import asruby.Ruby;
import asruby.runtime.Block;
import asruby.runtime.IRubyObject;
import asruby.runtime.MethodIndex;
import asruby.runtime.ThreadContext;

/**
 *
 * @author  jpetersen
 */
public class RubyException extends RubyObject  {

    private  var backtraceFrames:Array;
    private  var _backtrace:IRubyObject;
    public  var message:IRubyObject;
    public static var TRACE_HEAD: int =  8;
    public static var TRACE_TAIL: int =  4;
    public static var TRACE_MAX: int =  TRACE_HEAD + TRACE_TAIL + 6;

 
    public  function RubyException(runtime:Ruby, rubyClass:RubyClass, message:String=null){
        super(runtime, rubyClass);       
        this.message = message == null ? runtime.getNil() : runtime.newString(message);
    }
    
    private static var EXCEPTION_ALLOCATOR: Function =  
        function allocate(runtime:Ruby, klass:RubyClass):IRubyObject{
            var instance: RubyException =  new RubyException(runtime, klass);
            
            // for future compatibility as constructors move toward not accepting metaclass?
            instance.setMetaClass(klass);
            
            return instance;
        };

    
/*     private static var EXCEPTION_MARSHAL: ObjectMarshal =  new ObjectMarshal() {
        public void marshalTo(Ruby runtime, Object obj, RubyClass type,
                              MarshalStream marshalStream) throws IOException {
            var exc: RubyException =  (RubyException)obj;
            
            marshalStream.registerLinkTarget(exc);
            List<Variable> attrs = exc.getVariableList();
            attrs.add(new VariableEntry(
                    "mesg", exc.message == null ? runtime.getNil() : exc.message));
            attrs.add(new VariableEntry("bt", exc.getBacktrace()));
            marshalStream.dumpVariables(attrs);
        }

        public Object unmarshalFrom(Ruby runtime, RubyClass type,
                                    UnmarshalStream unmarshalStream) throws IOException {
            var exc: RubyException =  (RubyException)type.allocate();
            
            unmarshalStream.registerLinkTarget(exc);
            unmarshalStream.defaultVariablesUnmarshal(exc);
            
            exc.message = exc.removeInternalVariable("mesg");
            exc.set_backtrace(exc.removeInternalVariable("bt"));
            
            return exc;
        }
    }; */

    public static function createExceptionClass(runtime:Ruby):RubyClass{
        var exceptionClass: RubyClass =  runtime.defineClass("Exception", runtime.getObject(), EXCEPTION_ALLOCATOR);
        runtime.setException(exceptionClass);

        exceptionClass.setMarshal(EXCEPTION_MARSHAL);
        exceptionClass.defineAnnotatedMethods(RubyException);

        return exceptionClass;
    }

    public static function newException(runtime:Ruby, excptnClass:RubyClass, msg:String):RubyException{
        return new RubyException(runtime, excptnClass, msg);
    }
    
    public  function setBacktraceFrames(backtraceFrames:Array):void{
        this.backtraceFrames = backtraceFrames;
    }
    
    public  function getBacktrace():IRubyObject{
        if (_backtrace == null) {
            _backtrace = backtraceFrames == null ? getRuntime().getNil() : 
                ThreadContext.createBacktraceFromFrames(getRuntime(), backtraceFrames);
        }
        return backtrace;
    }

    public override function initialize(args:Array, block:Block):IRubyObject{
        if (args.length == 1) message = args[0];
        return this;
    }

    public  function backtrace():IRubyObject{
        return getBacktrace(); 
    }

    public  function set_backtrace(obj:IRubyObject):IRubyObject{
        if (obj.isNil()) {
            backtrace = null;
        } else if (!isArrayOfStrings(obj)) {
            throw getRuntime().newTypeError("backtrace must be Array of String");
        } else {
            backtrace = obj;
        }
        return backtrace();
    }
    
    public static function exception(context:ThreadContext, recv:IRubyObject, args:Array, block:Block):IRubyObject{
        return (recv).newInstance(context, args, block);
    }

    public  function exception(args:Array):RubyException{
        switch (args.length) {
            case 0 :
                return this;
            case 1 :
                if(args[0] == this) {
                    return this;
                }
                var ret: RubyException =  rbClone();
                ret.initialize(args, Block.NULL_BLOCK); // This looks wrong, but it's the way MRI does it.
                return ret;
            default :
                throw getRuntime().newArgumentError("Wrong argument count");
        }
    }

    public override function to_s():IRubyObject{
        if (message.isNil()) return getRuntime().newString(getMetaClass().getName());
        message.setTaint(isTaint());
        return message;
    }

    public  function to_str(context:ThreadContext):IRubyObject{
        return callMethod(context, MethodIndex.TO_S, "to_s");
    }

/*
    public override function inspect(context:ThreadContext):IRubyObject{
        var rubyClass: RubyModule =  getMetaClass();
        var exception: RubyString =  RubyString.objAsString(context, this);

        if (exception.getByteList().realSize == 0) return getRuntime().newString(rubyClass.getName());
        var sb: StringBuffer =  new StringBuffer("#<");
        sb.append(rubyClass.getName()).append(": ").append(exception.getByteList()).append(">");
        return getRuntime().newString(sb.toString());
    }

    public  function printBacktrace(errorStream:PrintStream):void{
        var backtrace: IRubyObject =  callMethod(getRuntime().getCurrentContext(), "backtrace");
        if (!backtrace.isNil() && backtrace instanceof RubyArray) {
            var elements: Array =  (backtrace.convertToArray()).toJavaArray();

            for ( var int:i = 1; i < elements.length; i++) {
                var stackTraceLine: IRubyObject =  elements[i];
                    if (stackTraceLine instanceof RubyString) {
                    printStackTraceLine(errorStream, stackTraceLine);
                }

                if (i == RubyException.TRACE_HEAD && elements.length > RubyException.TRACE_MAX) {
                    var hiddenLevels: int =  elements.length - RubyException.TRACE_HEAD - RubyException.TRACE_TAIL;
                            errorStream.print("\t ... " + hiddenLevels + " levels...\n");
                    i = elements.length - RubyException.TRACE_TAIL;
                }
            }
            }
    } 

    private  function printStackTraceLine(errorStream:PrintStream, stackTraceLine:IRubyObject):void{
            errorStream.print("\tfrom " + stackTraceLine + '\n');
    }
	*/
    private  function isArrayOfStrings(backtrace:IRubyObject):Boolean{
        if (!(backtrace instanceof RubyArray)) return false; 
            
        var elements: Array =  (backtrace).toJavaArray();
        
        for ( var int:i = 0 ; i < elements.length ; i++) {
            if (!(elements[i] instanceof RubyString)) return false;
        }
            
        return true;
    }
    public function getTarget():Object{
    	return null;
    }
     public function setTarget(obj:Object):Object{
    	return null;
    }
    public  function getException():RubyException{
    	return null;
    }
    public function getValue():IRubyObject{
    	return null;
    }
}
}